package myApp.KnorrAndroid.view;

import java.util.ArrayList;

import myApp.Constant.IntentConstants;
import myApp.KnorrAndroid.R;
import myApp.KnorrAndroid.common.ActionEvent;
import myApp.KnorrAndroid.common.KnorrInfo;
import myApp.KnorrAndroid.common.ModelEvent;
import myApp.KnorrAndroid.lib.network.http.HTTPClient;
import myApp.KnorrAndroid.lib.network.http.HTTPRequest;
import myApp.KnorrAndroid.ultils.KnorrLog;
import myApp.KnorrAndroid.ultils.StringUtil;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;

import com.google.code.microlog4android.appender.LogCatAppender;
import com.google.code.microlog4android.config.PropertyConfigurator;

public abstract class KnorrBaseActivity extends Activity implements
		DialogInterface.OnCancelListener {
	
	// chuoi action cua cac broadcast message
	public static final String KN_ACTION = "myApp.KnorrAndroid.action";
	// kiem tra activity da finish hay chua
	public boolean isFinished = false;
	// co nhan broadcast hay khong
	private boolean broadcast;
	
	private ArrayList<HTTPRequest> unblockReqs = new ArrayList<HTTPRequest>();
	private ArrayList<HTTPRequest> blockReqs = new ArrayList<HTTPRequest>();

	// dialog hien thi khi request
	private ProgressDialog progressDlg;

	// header view
	private View rlKnorrHeader;

	
	
	// broadcast receiver, nhan broadcast
	BroadcastReceiver receiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			int action = intent.getExtras().getInt("knorr.action");
			int hasCode = intent.getExtras().getInt("knorr.hashCode");
			if (hasCode != KnorrBaseActivity.this.hashCode()) {
				receiveBroadcast(action, intent.getExtras());
			}
		}
	};
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		 PropertyConfigurator.getConfigurator(this).configure();
		 if(KnorrLog.logger.getNumberOfAppenders()==0){
			 KnorrLog.logger.addAppender(new LogCatAppender());
		 }
		 KnorrInfo.getInstance().setAppContext(getApplicationContext());
		 KnorrInfo.getInstance().setActivityContext(this);
		if(savedInstanceState!=null){
			if(savedInstanceState.containsKey(IntentConstants.INTENT_GLOBAL_BUNDLE)){
				getIntent().putExtras(savedInstanceState.getBundle(IntentConstants.INTENT_GLOBAL_BUNDLE));
			}
			if (StringUtil.isNullOrEmpty(HTTPClient.sessionID)&&savedInstanceState
					.containsKey(IntentConstants.INTENT_SESSION_ID)) {
				HTTPClient.sessionID = savedInstanceState
						.getString(IntentConstants.INTENT_SESSION_ID);
			}
		}

		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		try {
			IntentFilter filter = new IntentFilter(KnorrBaseActivity.KN_ACTION);
			registerReceiver(receiver, filter);
			this.broadcast = true;
		} catch (Exception e) {
		}
	}
	
	
	/**
	 *  create voi tham so co nhan broadcast hay khong
	 *  @author: BangHN
	 *  @version: 1.0
	 *  @since: Dec 30, 2011
	 */
	protected void onCreate(Bundle savedInstanceState, boolean broadcast) {
		super.onCreate(savedInstanceState);
		 PropertyConfigurator.getConfigurator(this).configure();
		 if(KnorrLog.logger.getNumberOfAppenders()==0){
			 KnorrLog.logger.addAppender(new LogCatAppender());
		 }
		 KnorrInfo.getInstance().setAppContext(getApplicationContext());
		KnorrInfo.getInstance().setActivityContext(this);
		if(savedInstanceState!=null){
			if(savedInstanceState.containsKey(IntentConstants.INTENT_GLOBAL_BUNDLE)){
				getIntent().putExtras(savedInstanceState.getBundle(IntentConstants.INTENT_GLOBAL_BUNDLE));
			}
			if(savedInstanceState!=null){
				if(savedInstanceState.containsKey(IntentConstants.INTENT_GLOBAL_BUNDLE)){
					getIntent().putExtras(savedInstanceState.getBundle(IntentConstants.INTENT_GLOBAL_BUNDLE));
				}
				if (StringUtil.isNullOrEmpty(HTTPClient.sessionID)&&savedInstanceState
						.containsKey(IntentConstants.INTENT_SESSION_ID)) {
					HTTPClient.sessionID = savedInstanceState
							.getString(IntentConstants.INTENT_SESSION_ID);
				}
			}
		}

		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		this.broadcast = broadcast;
		if (broadcast) {
			try {
				IntentFilter filter = new IntentFilter(
						KnorrBaseActivity.KN_ACTION);
				registerReceiver(receiver, filter);
			} catch (Exception e) {
			}
		}

		
	}

	
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		if(getIntent().getExtras()!=null){
			outState.putBundle(IntentConstants.INTENT_GLOBAL_BUNDLE, getIntent().getExtras());
		}
		if(!StringUtil.isNullOrEmpty(HTTPClient.sessionID)){
			outState.putString(IntentConstants.INTENT_SESSION_ID, HTTPClient.sessionID);
		}
		super.onSaveInstanceState(outState);
	}
	
	
	@Override
	public void finish() {
		isFinished = true;
		super.finish();
	}

	@Override
	public void finishActivity(int requestCode) {
		isFinished = true;
		super.finishActivity(requestCode);
	}
	
	
	
	@Override
	public void setContentView(int layoutResID) {
		super.setContentView(R.layout.layout_knorr);
		LinearLayout mainContent = (LinearLayout) findViewById(R.id.llContent);
		LayoutInflater inflater = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		inflater.inflate(layoutResID, mainContent);

		initialize();
	}

	@Override
	public void setContentView(View view) {
		// TODO Auto-generated method stub
		super.setContentView(R.layout.layout_knorr);
		LinearLayout main = (LinearLayout) findViewById(R.id.llContent);
		main.addView(view);
		initialize();
	}

	private void initialize() {
		LinearLayout rootView = (LinearLayout) findViewById(R.id.llKnorrMain);
		LayoutInflater inflater = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		rlKnorrHeader = inflater.inflate(R.layout.knorr_header, null);
		//rootView.addView(rlKnorrHeader, 0);
	}

	@Override
	protected void onDestroy() {
		try {
			unregisterReceiver(receiver);
		} catch (Exception e) {
		}
		removeAllProcessingRequest();
		System.gc();
		System.runFinalization();
		System.gc();
		super.onDestroy();
	}

	
	
	
	public void onCancel(DialogInterface dialog) {
		// dang hien thi progressDialog => bam nut back
		// TODO Auto-generated method stub
		if (dialog == progressDlg) {
			cancelRequest(this.blockReqs);
		}
	}
	
	
	/**
	 * show msg notify to user
	 * 
	 * @author: BangHN
	 * @version: 1.0
	 * @since: Oct 12, 2011
	 */
	public AlertDialog showDialog(String mes) {
		AlertDialog alertDialog = new AlertDialog.Builder(this).create();
		alertDialog.setMessage(mes);
		alertDialog.setButton("Đồng ý", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				// xu ly vao controller o day.....
				dialog.dismiss();
				return;

			}
		});
		alertDialog.show();
		return alertDialog;
	}

	public void removeAllProcessingRequest() {
		cancelRequest(blockReqs);
		cancelRequest(unblockReqs);
	}

	public AlertDialog showDialogConfirm(String mes, String ok, String cancel) {
		AlertDialog alertDialog = new AlertDialog.Builder(this).create();
		alertDialog.setMessage(mes);
		alertDialog.setButton(ok, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				showProgressDialog(StringUtil.getString(KnorrBaseActivity.this,
						R.string.loading));
				dialog.dismiss();
				return;

			}
		});
		alertDialog.setButton2(cancel, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				return;

			}
		});

		alertDialog.show();

		return alertDialog;
	}

	public void showProgressDialog(String content) {
		showProgressDialog(content, true);
	}

	public void showProgressDialog(String content, boolean cancleable) {
		progressDlg = ProgressDialog.show(this, "", content, true, true);
		progressDlg.setCancelable(cancleable);
		progressDlg.setOnCancelListener(this);
	}

	public void closeProgressDialog() {
		if (progressDlg != null) {
			progressDlg.dismiss();
			progressDlg = null;
		}
	}

	public void showProgressPercentDialog(String content) {
		progressDlg = new ProgressDialog(this);
		progressDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progressDlg.setMessage(content);
		progressDlg.setCancelable(false);
		progressDlg.show();
	}

	public void updateProgressPercentDialog(int percent) {
		if (progressDlg != null) {
			progressDlg.setProgress(percent);
		}
	}

	public void closeProgressPercentDialog() {
		if (progressDlg != null) {
			progressDlg.dismiss();
			progressDlg = null;
		}
	}

	public void removeProcessingRequest(HTTPRequest req, boolean isBlock) {
		if (isBlock) {
			cancelRequest(blockReqs, req);
		} else {
			cancelRequest(unblockReqs, req);
		}
	}

	
	public void addProcessingRequest(HTTPRequest req, boolean isBlock) {
		if (isBlock) {
			blockReqs.add(req);
		} else {
			unblockReqs.add(req);
		}
	}
	
	private void cancelRequest(ArrayList<HTTPRequest> arrReq) {
		HTTPRequest req = null;
		for (int i = 0, n = arrReq.size(); i < n; i++) {
			req = arrReq.get(i);
			req.setAlive(false);
		}
		arrReq.clear();
	}

	private void cancelRequest(ArrayList<HTTPRequest> arrReq, HTTPRequest req) {
		HTTPRequest curReq = null;
		for (int i = 0, n = arrReq.size(); i < n; i++) {
			curReq = arrReq.get(i);
			if (curReq == req) {
				arrReq.remove(i);
				req.setAlive(false);
				break;
			}
		}
		arrReq.clear();
	}
	
	
	/**
	 *  send broadcast toi cac view
	 *  @author: BangHN
	 *  @version: 1.0
	 *  @since: Dec 30, 2011
	 */
	public void sendBroadcast(int action, Bundle bundle) {
		Intent intent = new Intent(KN_ACTION);
		bundle.putInt("knorr.action", action);
		bundle.putInt("knorr.hashCode",intent.getClass().hashCode());
		intent.putExtras(bundle);
		sendBroadcast(intent);
	}
	
	/**
	 *  nhan msg khi co intent sent boi broadcast
	 *  @author: BangHN
	 *  @version: 1.0
	 *  @since: Dec 30, 2011
	 */
	public void receiveBroadcast(int action, Bundle bundle) {
		
	}
	

	/**
	 *  Xu ly model tren tang view
	 *  @author: BangHN
	 *  @version: 1.0
	 *  @since: Jan 1, 2012
	 */
	public void handleModelViewEvent(ModelEvent modelEvent) {
		ActionEvent e = modelEvent.getActionEvent();
			switch (e.action) {
			}
	}


	/**
	 *  Xu ly loi model tren tang view
	 *  @author: BangHN
	 *  @version: 1.0
	 *  @since: Jan 1, 2012
	 */
	public void handleErrorModelViewEvent(ModelEvent modelEvent) {
		// TODO Auto-generated method stub
		
	}
	
	
}
